package com.woniuxy.portal.config;

import com.woniuxy.portal.common.constant.RedisConstant;
import com.woniuxy.portal.entity.Book;
import com.woniuxy.portal.repository.BookRepository;
import com.woniuxy.portal.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * CommandLineRunner
 * 1、Spring Boot提供了CommandLineRunner接口，您可以使用他完成项目启动时候执行一些初始化操作。
 * 2、加载配置、初始化数据库连接、预加载数据（数据预热）
 */
@Component
public class InitTop10BookRunner implements CommandLineRunner {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IBookService bookService;
//    @Autowired
//    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private BookRepository bookRepository;

    @Override
    public void run(String... args) throws Exception {
        // 查询所有图书
        List<Book> bookList = bookService.list();

        // 数据同步到es的索引库
        //elasticsearchRestTemplate.save(bookList);
        bookRepository.saveAll(bookList);

        // 遍历图书，加入到Redis的zset集合，buyCount购买量作为分值
        bookList.forEach(book -> {
            redisTemplate.opsForZSet().add(RedisConstant.BOOK_LIST,book, book.getBuycount());
            // 数据预热：把库存数据加载到Redis中. 每一本书对应一个库存
            redisTemplate.opsForHash().put("storage",book.getId().toString(),book.getStorecount());
        });
    }
}
